package com.yesjpt.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yesjpt.domain.User;
import com.yesjpt.page.PageTableRequest;

import net.sourceforge.pinyin4j.PinyinHelper;

public class StringUtil {
	// 解码
	public static String decodeUnicode(String unicode) {
		if (unicode == null || "".equals(unicode)) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		int i = -1;
		int pos = 0;
		while ((i = unicode.indexOf("\\u", pos)) != -1) {
			sb.append(unicode.substring(pos, i));
			if (i + 5 < unicode.length()) {
				pos = i + 6;
				sb.append((char) Integer.parseInt(unicode.substring(i + 2, i + 6), 16));
			}
		}
		return sb.toString();
	}

	// 编码
	public static String encodeUnicode(String string) {
		if (string == null || "".equals(string)) {
			return null;
		}
		StringBuffer unicode = new StringBuffer();
		for (int i = 0; i < string.length(); i++) {
			char c = string.charAt(i);
			unicode.append("\\u" + Integer.toHexString(c));
		}
		return unicode.toString();
	}

	public static Map<String, String> queryString2Map(String paramStr) {
		String[] params = paramStr.split("&");
		Map<String, String> resMap = new HashMap<String, String>();
		for (int i = 0; i < params.length; i++) {
			String[] param = params[i].split("=");
			if (param.length >= 2) {
				String key = param[0];
				String value = param[1];
				for (int j = 2; j < param.length; j++) {
					value += "=" + param[j];
				}
				resMap.put(key, value);
			}
		}
		return resMap;
	}

	public static String safeSql(String sql) {
		if (sql == null || sql.length() == 0)
			return "";
		sql = sql.toLowerCase();
		return sql.replace("delete", "").replace("update", "").replace("insert", "").replace("drop", "")
				.replace("alter", "");
	}

	// s = "{appId=002, start=0, length=10, orderBy= order by convert(t.nickname
	// using gbk) asc, draw=3, cond=, status=}".replace("{", "").replace("}", "");
	public static Map<String, Object> str2Map(String s) {
		Map<String, Object> map = new HashMap<String, Object>();
		s = s.replace("{", "").replace("}", "");
		for (String a : s.split(", ")) {
			if (a == null || a.length() == 0)
				continue;
			String[] e = a.split("=");
			if (e == null || e.length < 2)
				continue;
			map.put(e[0], e[1]);
		}
		return map;

	}

	public static String toUrl(String action, PageTableRequest request) {
		JSONObject param = JSONObject.parseObject(JSONObject.toJSONString(request));
		String url = "";
		for (String key : param.keySet()) {
			url += key + "=" + param.get(key) + "&";
		}
		if (url.indexOf("&") > 0)
			url = url.substring(0, url.lastIndexOf("&"));
		try {
			return action + "?" + URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String fixUrl(String url) {
		// L.i("url修正前：" + url);
		if (url == null || url.length() == 0)
			return "";
		url = url.replace("://", "@@@").replace("//", "/").replace("@@@", "://");
		if (url.endsWith("/"))
			url = url.substring(0, url.lastIndexOf("/"));
		// L.i("url修正后：" + url);
		return url;
	}

	public static String fixNull(String s) {
		return s == null ? "" : s;
	}

	public static String upperCase1(String str) {
		if (str == null || str.length() == 0)
			return "";
		return str.substring(0, 1).toUpperCase() + str.substring(1);
	}

	// 将汉字转换为拼音的全拼的大写，非汉字的原样输出
	public static StringBuilder getQuanPin(String str) {

		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < str.length(); i++) {
			char s = str.charAt(i);

			/**
			 * PinyinHelper.toHanyuPinyinStringArray说明： 1、参数传中文，返回值是这个汉字的小写拼音+这个汉字是几声。比如：参数传
			 * "汉 "，return的String[ ] 就是 [han4] 2、当传字母时，返回值是null。
			 * 注意：toHanyuPinyinStringArray接收的参数是char，意思就是说一次只能转换一个，
			 * 比如“美”是string，toHanyuPinyinStringArray不能直接接收， 每次只能传一个，返回的那个String数组里肯定只有一个元素。
			 */
			String[] s1 = PinyinHelper.toHanyuPinyinStringArray(s);

			if (null == s1) {
				sb.append(s);
			} else {
				String up = s1[0].substring(0, s1[0].length() - 1);
				up = up.toUpperCase();
				sb.append(up);
			}
		}
		return sb;
	} // 有效的筛选

	public static Boolean isValidFilter(String s) {
		if (s != null && s.length() > 0 && !"-1".equals(s) && !"undefined".equals(s))
			return true;
		return false;
	}

	public static String delHTMLTag(String htmlStr) {
		if (htmlStr == null)
			return "";
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
		String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll(""); // 过滤script标签

		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll(""); // 过滤style标签

		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll(""); // 过滤html标签

		return htmlStr.trim(); // 返回文本字符串
	}

	public static int getLength(String s) {
		if (s == null)
			return 0;
		s = delHTMLTag(s).replace("\n", "").replace("\t", "");
		// System.out.println(s);
		return delHTMLTag(s).length();
	}

	public static void t(User a) {
		a.setNickname("陈剑波");
	}

	public static void t(Integer a) {
		a = 800;
	}

	public static void main(String[] args) {
		System.out.println(isMobile(null));
		User a = new User();
		a.setNickname("黄大仙");
		t(a);
		System.out.println("a.nickname = " + a.getNickname());
		Integer i = new Integer(600);
		t(i);
		System.out.println("i = " + i);
		// System.out.println(formatNumTo4Str(10));
		// System.out.println(rand6());
		// System.out.println("_".charAt(0));
		// System.out.println(replaceSensitiveWords("法轮功", '.'));
		// System.out.println(isNull(null));
		// System.out.println(isInclude("2500",
		// "${money>=2000+1000&&money<=4000+100}"));
		// System.out.println(isInclude("2500", "${12*10}"));
		// System.out.println(isInclude("2500", "${120 > 3}"));
	}

	// 升级版
	/*
	 * public static Boolean rule(List<Map<String, Object>> map, String elString){
	 * String elValue; String el = elString.substring(elString.indexOf("{")+1,
	 * elString.indexOf("}")); ScriptEngineManager manager = new
	 * ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js");
	 * engine.put("money", elValue); boolean eval = false; try { eval = (boolean)
	 * engine.eval(el); } catch (ScriptException e) { // TODO Auto-generated catch
	 * block e.printStackTrace(); } return eval; }
	 */
	// 构建极其模糊的查询条件，e.g: 【上海吊车厂】可以从【上吊】查出来
	public static String cond(String cond) {
		if (cond == null || cond.length() == 0)
			return "%";
		String fullSearch = ResourceBundle.getBundle("config").getString("fullSearch");
		if (fullSearch == null || fullSearch.length() == 0 || "false".equals(fullSearch))
			return "%" + cond + "%";
		String s = "%";
		for (int i = 0; i < cond.length(); i++) {
			s += cond.toCharArray()[i] + "%";
		}
		return s;
	}

	// 将收到的消息解析为map
	public static HashMap<String, String> resolveMsg2Map(String s) {
		if (s == null || s.length() == 0)
			return null;
		HashMap<String, String> map = new HashMap<String, String>();
		for (String item : s.split("&")) {
			String[] arr = item.split("=");
			if (arr == null || arr.length == 1)
				continue;
			map.put(arr[0], arr[1]);
		}
		return map;
	}

	// 产生guid()
	public static String genGuid() {
		// String s = UUID.randomUUID().toString();
		// 去掉“-”符号
		// return
		// (s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24)).toUpperCase();
		return UUIDHexGenerator.generate();
	}

	public static <T> HashMap<String, Object> where(Class<T> t) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		String s = "(";
		int i = 1;
		for (Field f : t.getDeclaredFields()) {
			if (f.getType().getName().equalsIgnoreCase("java.lang.String")) {
				s += " or d." + f.getName() + " like ?" + i++;
			}
		}
		map.put("where", s.replace("( or ", "(") + ")");
		map.put("count", i - 1);
		return map;
	}

	/**
	 * 生成where后台的括号，里面有很多 like 返回的map.where就是sql语句中where后面的部分，而map.count是参数的个数
	 */
	public static String ids2InIds(String ids) {
		if (ids == null || ids.length() == 0) {
			return "()";
		}
		String s = "";
		String[] arr = ids.split(",");
		for (int i = 0; i < arr.length; i++) {
			s += "'" + arr[i] + "',";
		}
		return "(" + s.substring(0, s.length() - 1) + ")";
	}

	// 在字符串的每个字符之间插入分隔符
	public static String replaceSensitiveWords(String para, char c) {
		int length = para.length();
		char[] value = new char[length << 1];
		for (int i = 0, j = 0; i < length; ++i, j = i << 1) {
			value[j] = para.charAt(i);
			value[1 + j] = c;
		}
		String s = new String(value);
		return s.substring(0, s.length() - 1);
	}

	/**
	 * 将数字格式化为3位字符串，不够的用0补齐 例如： 数字3 可一个格式为 003 数字 10 格式为010
	 * 
	 * @param num
	 * @return
	 */
	public static String rand(int length) { // length表示生成字符串的长度
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static String randNum(int length) { // length表示生成字符串的长度
		String base = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static String rand6() {
		String s = String.valueOf(Math.round(Math.random() * 1000000));
		if (s.length() == 6)
			return s;
		return rand6();
	}

	public static String formatNumTo3Str(int num) {
		return String.format("%03d", num);

	}

	public static String Str2In(String ids) {
		if (ids == null || ids.length() == 0) {
			return "";
		}
		String s = "";
		String[] arr = ids.split(",");
		for (int i = 0; i < arr.length; i++) {
			s += "'" + arr[i] + "',";
		}
		return s.substring(0, s.length() - 1);
	}

	// 填充0
	public static final String formatNumLength(Object in, int length) {
		if (in == null || "".equals(in.toString()))
			in = "0";
		Long input = Long.parseLong(in.toString());
		String r = null;
		if (Long.toString(input).length() >= length) {
			r = Long.toString(input);
		} else {
			String zero = "";
			for (int i = 0; i < length - Long.toString(input).length(); i++) {
				zero += "0";
			}
			r = zero + input;
		}
		return r;
	}

	public static List<HashMap<String, Object>> str2HashMap(String str) {
		HashMap<String, Object> m = new HashMap<String, Object>();
		List<HashMap<String, Object>> all = new LinkedList<HashMap<String, Object>>();
		JSONArray array = JSONArray.parseArray(str);
		for (int i = 0; i < array.size(); i++) {
			JSONObject o = array.getJSONObject(i);
			m = new HashMap<String, Object>();
			m.putAll(o);
			all.add(m);
		}
		return all;
	}

	// 一个字符串数组是否包含另外一个字符串
	public static boolean contain(String[] array, String str) {
		for (int i = 0; i < array.length; i++) {
			if (array[i].equals(str)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 将数字格式化为4位字符串，不够的用0补齐 例如： 数字3 可一个格式为 0003 数字 10 格式为0010
	 * 
	 * @param num
	 * @return
	 */
	public static String formatNumTo4Str(int num) {
		return String.format("%04d", num);

	}

	/**
	 * 将数字格式化为3位字符串，不够的用0补齐 例如： 数字3 可一个格式为 003 数字 10 格式为010
	 * 
	 * @param num
	 * @return
	 */
	public static String formatNumToNStr(int strLength, int num) {
		return String.format("%0" + strLength + "d", num);

	}

	/**
	 * 调用java的正则表达式匹配方法
	 * 
	 * @param patternStr
	 * @param txt
	 * @return
	 */
	private static boolean matcher(String patternStr, String txt) {
		Pattern p = Pattern.compile(patternStr);
		Matcher matcher = p.matcher(txt);
		return matcher.matches();
	}

	/**
	 * 验证字符串是否全部是数字
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isNumber(String txt) {
		if (txt == null)
			return false;
		String patternStr = "[0-9]*";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否全部是字母
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isLetter(String txt) {
		if (txt == null)
			return false;
		String patternStr = "[a-zA-Z]*";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否是字母和数字组成
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isLetterOrNumber(String txt) {
		if (txt == null)
			return false;
		String patternStr = "^[A-Za-z0-9]+$";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否含有中文
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isHasChinese(String txt) {
		if (txt == null)
			return false;
		final String patternStr = "^[\u4e00-\u9fa5]+$";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否以字母开头
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isStartWithLetter(String txt) {
		if (txt == null)
			return false;
		String patternStr = "[0-9]*";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否是email地址
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isEmail(String txt) {
		if (txt == null)
			return false;
		String patternStr = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证是否是电话号码
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isPhoneNumber(String txt) {
		if (txt == null)
			return false;
		String patternStr = "\\d{3}-\\d{8}|\\d{4}-\\d{7}|\\d{8}";
		return matcher(patternStr, txt);
	}

	public static boolean isMobile(String txt) {
		if (txt == null)
			return false;
		String patternStr = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否是邮政编码(中国)
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isZipCode(String txt) {
		if (txt == null)
			return false;
		String patternStr = "[0-9]*";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否是身份证号
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isIdCard(String txt) {
		if (txt == null)
			return false;
		String patternStr = "\\d{15}|\\d{18}";
		return matcher(patternStr, txt);
	}

	/**
	 * 验证字符串是否是IP地址
	 * 
	 * @param txt
	 * @return
	 */
	public static boolean isIpAddress(String txt) {
		if (txt == null)
			return false;
		String patternStr = "\\d+\\.\\d+\\.\\d+\\.\\d+";
		return matcher(patternStr, txt);
	}

	// 是否为空
	public static boolean isNotNull(Object o) {
		if (o != null && o.toString().length() > 0) {
			return true;
		}
		return false;
	}

	// 是否为空
	public static boolean isNull(Object o) {
		if (o == null || o.toString().length() == 0)
			return true;
		return false;
	}

	/**
	 * 判断是否为中文
	 * 
	 * @param str 入参
	 * @return true:中文false:非中文
	 */
	public static boolean isChineseChar(String str) {
		if (str == null)
			return false;
		boolean temp = false;
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			temp = true;
		}
		return temp;
	}

	public static String toUtf8(String s) {
		if (isChineseChar(s)) {
			try {
				s = new String(s.getBytes("iso8859-1"), "utf-8");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return s;
	}

}
